<template>
  <div v-loading="loading">
    <i ref="backbutton" @click="handleBack()" class="el-icon-back wl-back"> 返回</i>
    <div class="wl-task-deploy__header">
      <span class="title">{{task.project_name}}</span>
      <span class="title">/</span>
      <span class="title">{{task.name}}</span>
      <el-button @click="submitStart()" type="success" :disabled="!enableDeploy">{{enableDeploy&&errorFlag?'重新执行':'开始'}}</el-button>
      <!-- <el-button @click="test()" type="success">test</el-button> -->
    </div>
    <!-- task chart -->
    <task-chart ref="TaskChart"></task-chart>
    <!-- task log -->
    <task-log ref="TaskLog"></task-log>
  </div>
</template>

<script>
import io from 'socket.io-client'
import TaskChart from '@/views/walle/components/task/TaskChart'
import TaskLog from '@/views/walle/components/task/TaskLog'
import { getTasks, getTask } from '@/api/task'

export default {
  name: 'ViewTask',
  components: {
    TaskChart,
    TaskLog
  },
  data() {
    return {
      loading: false,
      params: {
        context: {},           // 父页面传递过来的参加，返回时带给父页面恢复上下文
        data: {}
      },
      task: {},
      enableDeploy: false,
      errorFlag: false,
      showMessageFlag: true,
      websock: null
    }
  },
  mounted() {
    const params = this.$route.params
    this.params.context = params.context
    this.params.data = params.data
    this.initTaskData(this.params.data.id)
  },
  beforeDestroy() {
    this.websock.close()
  },
  methods: {
    // test() {
    //   this.$refs.TaskLog.addLog({
    //     cmd: "cd /home/service/walle2/mytest && sleep 5s",
    //     error: "",
    //     host: "172.16.167.36",
    //     sequence: 6,
    //     stage: "post_release",
    //     status: 0,
    //     success: "",
    //     user: "root"
    //   })
    // },
    handleBack() {  // 返回
      this.$router.replace({name:'WalleDeploy', params: this.params.context})
    },
    submitStart() {
      this.enableDeploy = false
      this.showMessageFlag = true
      this.$refs.TaskChart.startDo()
      this.$refs.TaskLog.clearLog()
      this.websock.emit('deploy', {task: this.task.id})
    },
    initTaskData(taskid) { // 获取上线单信息
      this.loading = true
      getTask(taskid).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        this.task = response.data.data
        this.initWebSocket()
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '复制失败!' });
      })
    },
    initWebSocket() {
      // 创建websocket连接
      this.websock = io('/walle', {
        path:'/socket.io', 
        transports: ['websocket', 'polling'], // ['polling', 'websocket']
        autoConnect: false
      }) 
      // 系统事件处理
      this.websock.on('connect', this.onConnect)                     // 打开连接
      this.websock.on('reconnect', this.onReconnect)                 // 打开连接
      this.websock.on('disconnect', this.onDisconnect)               // 关闭连接
      this.websock.on('error', this.onError)                         // 连接异常
      this.websock.on('connect_timeout', this.onConnectTimeout)      // 连接异常 
      this.websock.on('connect_error', this.onConnectError)          // 连接异常
      this.websock.on('reconnect_error', this.onReconnectError)      // 连接异常
      this.websock.on('reconnect_failed', this.onReconnectFailed)    // 连接异常
      this.websock.on('ping', this.onPing)                           // Ping
      this.websock.on('pong', this.onPong)                           // Pong
      //应用内消息处理：pong,close  结构体event定义：console,finish,ping:pong,error,commits,tags,branches,forbidden,connect,disconnect
      this.websock.on('construct', this.doMessage)          // 上线单发布结构消息
      this.websock.on('console', this.doMessage)            // 服务器发送控制台消息
      this.websock.on('branches', this.doMessage)
      this.websock.on('tags', this.doMessage)
      this.websock.on('commits', this.doMessage)
      this.websock.on('success', this.doSuccessMessage)
      this.websock.on('fail', this.doFailMessage)
      // 打开websocket连接
      this.websock.open()
    },
    onConnect(data) {
      console.log('打开连接 - ', data)
      this.websock.emit('open', {task: this.task.id})
      this.websock.emit('logs', {task: this.task.id})
    },
    onReconnect(data) {
      console.log('重新连接 - ', data)
      this.onConnect()
    },
    onDisconnect(data) {
      console.log('关闭连接 - ', data)
    },
    onConnectError(error) {
      console.log('连接错误', error)
    },
    onError(error) {
      console.log('错误 - ', error)
    },
    onConnectTimeout(timeout) {
      console.log('连接超时 - ', timeout)
    },
    onReconnectError(error) {
      console.log('重新连接错误 - ', error)
    },
    onReconnectFailed(error) {
      console.log('重新连接失败 - ', error)
    },
    onPing(data) {
      console.log('ping - ', data)
    },
    onPong(data) {
      console.log('pong - ', data)
    },
    doMessage(data) {
      console.log(data)
      switch(data.event) {
        case "construct": this.doConstructEvent(data.event, data.data); break  // 任务结构图
        case "forbidden" : this.doForbidden(data.event, data.data); break
        case "task:console":
        case "console": this.doConsoleEvent(data.event, data.data); break    // 任务控制台日志
        case "finish": this.doFinishEvent(data.event, data.data); break      // 任务完成
      }
    },
    doSuccessMessage(data) {  // 上线完成
      console.log('success', data)
      this.errorFlag = false
      switch(data.event) {
      case "finish": 
        this.$refs.TaskChart.doSuccess(data.data)
        if (!data.data.host) {
          if (this.showMessageFlag) {
            this.$message({ type:'success', message:data.data.message})
          }
        }
        break
      }
    },
    doFailMessage(data) {  // 上线失败
      console.log('fail', data)
      this.errorFlag = true
      switch(data.event) {
      case "finish": 
        this.enableDeploy = true
        this.$refs.TaskChart.doFail(data.data)
        if (this.showMessageFlag) {
          this.$message({ type:'error', message:data.data.message})
        }
        break
      }
    },
    // --------------------
    doConstructEvent(event, data) { // 处理任务结构图消息
      this.enableDeploy = data.enable_online
      this.$refs.TaskChart.setConstruct(data)
      this.$refs.TaskLog.setServerCount(data.servers_info.length)
    },
    doForbidden(event, data) {
      this.$message({ type:'error', message:'任务当前状态禁止操作！'})
    },
    doConsoleEvent(event, data) {
      this.$refs.TaskChart.addStepLog(data)
      this.$refs.TaskLog.addLog(data)
    },
    doFinishEvent(event, data) {
      this.errorFlag = (event === 'fail')
      this.$refs.TaskChart.doFinish(data, event)
      if (this.showMessageFlag) {
        this.$message({ type:'info', message:data.message})
      }
    }
  }
}
</script>

<style scoped>
  .wl-back {
    color: #1890ff;
    font-size: 14px;
    cursor: pointer;
  }
  .wl-task-deploy__header {
    line-height: 40px;
    height: 40px;
    margin-bottom: 20px;
  }
  .wl-task-deploy__header .title {
    margin-right: 10px;
    font-size: 16px;
  }
</style>
